package cn.renxuan.service.weather;

import java.net.HttpURLConnection;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;

import cn.renxuan.entity.FS_DomesticWeather;
import cn.renxuan.enums.EWeatherDataSource;
import cn.renxuan.http.HttpUtil;
import cn.renxuan.http.aliyun.SignUtil;
import cn.renxuan.http.constant.HttpHeader;
import cn.renxuan.service.weather.json.LunDearBase;
import cn.renxuan.service.weather.json.LunDearWeather;
import cn.renxuan.service.weather.mapper.LunDearWeatherMapper;
import org.mapstruct.Mapper;

@Service
public class LunDearWeatherService implements IWeatherService {
    public LunDearWeatherService() {

    }

    private static final Map<String, DayOfWeek> CHINESE_WEEKDAY_MAP = new HashMap<>();
    static {
        CHINESE_WEEKDAY_MAP.put("星期一", DayOfWeek.MONDAY);
        CHINESE_WEEKDAY_MAP.put("星期二", DayOfWeek.TUESDAY);
        CHINESE_WEEKDAY_MAP.put("星期三", DayOfWeek.WEDNESDAY);
        CHINESE_WEEKDAY_MAP.put("星期四", DayOfWeek.THURSDAY);
        CHINESE_WEEKDAY_MAP.put("星期五", DayOfWeek.FRIDAY);
        CHINESE_WEEKDAY_MAP.put("星期六", DayOfWeek.SATURDAY);
        CHINESE_WEEKDAY_MAP.put("星期日", DayOfWeek.SUNDAY);
    }

    /**
     * 验证给定年月日和星期几是否匹配
     * 
     * @param year           年份
     * @param month          月份 (1-12)
     * @param day            日期 (1-31)
     * @param chineseWeekday 中文星期几 ("星期一"到"星期日")
     * @return true如果匹配，false如果不匹配或日期无效
     */
    public static boolean validateDate(int year, int month, int day, String chineseWeekday) {
        try {
            // 转换中文星期为DayOfWeek
            DayOfWeek expectedDayOfWeek = CHINESE_WEEKDAY_MAP.get(chineseWeekday);
            if (expectedDayOfWeek == null) {
                return false;
            }

            // 创建LocalDate对象
            LocalDate date = LocalDate.of(year, month, day);

            // 比较实际的星期几
            return date.getDayOfWeek() == expectedDayOfWeek;
        } catch (Exception e) {
            // 捕获无效日期异常(如2月30日)
            return false;
        }
    }

    /*
     * 格式：07月09日(星期三) 15:00
     */
    private LocalDateTime getReportTime(String sourceReportTime) {
        int month = Integer.parseInt(sourceReportTime.substring(0, 2));
        int day = Integer.parseInt(sourceReportTime.substring(3, 5));
        String chineseWeekday = sourceReportTime.substring(7, 10);
        int hour = Integer.parseInt(sourceReportTime.substring(12, 14));
        int minute = Integer.parseInt(sourceReportTime.substring(15, 17));
        // 获取当前年份
        int year = LocalDate.now().getYear();
        // 验证日期和星期几是否匹配
        if (!validateDate(year, month, day, chineseWeekday)) {
            year = year - 1;
            // 如果不匹配，尝试使用前一年的日期
            if (!validateDate(year, month, day, chineseWeekday)) {
                throw new IllegalArgumentException("Invalid date or weekday: " + sourceReportTime);
            } else {
                // 如果匹配，返回前一年的日期
                return LocalDateTime.of(year, month, day, hour, minute);
            }
        } else {
            // 创建LocalDateTime对象
            return LocalDateTime.of(year, month, day, hour, minute);
        }
    }

    public FS_DomesticWeather getDomesticWeather(Map<String, String> querys, Map<String, String> headers)
            throws Exception {
        FS_DomesticWeather retVal = null;

        WeatherConfig weatherConfig = WeatherHelper.getWeatherConfigByPropName("realtimeweather-configKey");
        LocalDateTime now = LocalDateTime.now();
        LunDearBase<LunDearWeather> lundearWeather = null;
        if (headers == null) {
            headers = new HashMap<String, String>();
        }

        if (querys != null && querys.size() > 0) {
            // 使用 TreeMap 自动排序
            querys = new TreeMap<>(querys);
        }
        headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, "application/json; charset=utf-8");
        headers = SignUtil.initialBasicHeader(weatherConfig.getRealapiurl(), weatherConfig.getApikey(),
                weatherConfig.getApisecret(), "GET", headers, querys, null, null);
        // 从网络获取天气数据
        lundearWeather = HttpUtil
                .<LunDearBase<LunDearWeather>>getAndResTxt(new TypeReference<LunDearBase<LunDearWeather>>() {
                },
                        weatherConfig.getBasepath(),
                        weatherConfig.getRealapiurl(), 5000, headers, querys);

        // lundearWeather = new LunDearBase<LunDearWeather>();
        if (lundearWeather != null) {
            retVal = LunDearWeatherMapper.INSTANCE.toDomesticWeather(lundearWeather);
            if (retVal != null) {
                String dateTimeStr = String.format("%s %s",
                        lundearWeather.getData().getNow().getDate(),
                        lundearWeather.getData().getNow().getTime());
                // String dateTimeStr = String.format("%s %s", "07月09日(星期三)",
                // "15:00");

                // 转换为LocalDateTime
                LocalDateTime reportTime = getReportTime(dateTimeStr);

                retVal.setDatasource((byte) EWeatherDataSource.LunDear.ordinal());
                retVal.setReporttime(reportTime);
                retVal.setCitycode(retVal.getCountycode().substring(0, 4));
                retVal.setProvincecode(retVal.getCountycode().substring(0, 2));
                retVal.setYear((short) now.getYear());
                retVal.setMonth((byte) now.getMonth().getValue());
                retVal.setDay((byte) now.getDayOfMonth());
                retVal.setHour((byte) now.getHour());
                retVal.setMinute((byte) now.getMinute());
                retVal.setSecond((byte) now.getSecond());
                retVal.setCreationtime(now);
                retVal.setIsdeleted(false);
                retVal.setRestxt(lundearWeather.getRestxt());
            }
        }
        return retVal;
    }
}

// Request：
// Url:
// http://a9ebfbb870874b59b47ce77a1af8c3cb-cn-beijing.alicloudapi.com/lundear/weather1d?areaCode=321102&need1hour=1&need3hour=1
// Header:
// {"X-Ca-Timestamp":"1752370746633","gateway_channel":"http","X-Ca-Key":"204912883","x-ca-nonce":"898b5ffb-d039-42a8-bbe4-02d001ac24a7","X-Ca-Request-Mode":"DEBUG","X-Ca-Stage":"RELEASE","X-Ca-Supervisor-Token":"eyJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NTIzNzA3NDYsIm5iZiI6MTc1MjM3MDY4NiwiaXNzIjoiQWxpeXVuQXBpR2F0ZXdheSIsInJvbGUiOiJ1c2VyIiwiYXVkIjoiYXBpLXNoYXJlZC12cGMtMDAyIiwiZXhwIjoxNzUyMzcxNjQ2LCJqdGkiOiJhMTQyNzYwNjkzN2M0NGY2YThmNmQ5ODRlMGExNjBiNSIsImFjdGlvbiI6IkRFQlVHIiwidWlkIjoiMTAwNjc4OTI3MTM5ODY1OSJ9.b1LV0jRhb-ecxFiLwNIbMD6o64ICf1kdzbaXOHRELBOJb4w7k0Lp3BJCgf__OC7I2DvQrrDb-BbBmC2NmcKaUhEPwTyNxA3_saaVnBxInk88M96pBJitDAecRPVXFeY4cCgiKBNrUI2e5P6bohzouopPB4qj7WyXdNJ1P7fkENcAACTxdhEaqqcu7Q8oUCd9KTYAU36B-5xUBajggkThbySUnYtxhKGpE9iDuU5-0gBmaqe4wO_oln0AGmfelSrdW4N-KBfyEw2_2ff_rUnksrru8DRV2UpPsE16bOneCTjWh8IS6KhulhJ44rkO3fjmhF1KLDeHSMnQwOMmOuHdTg","Host":"a9ebfbb870874b59b47ce77a1af8c3cb-cn-beijing.alicloudapi.com","X-Ca-Signature":"GXSw0aljDzJLoTNcarhVDY1WckXT1iuAiuao8Cn816c=","Content-Type":"text/html","X-Ca-Signature-Headers":"X-Ca-Timestamp,X-Ca-Key,X-Ca-Request-Mode,X-Ca-Stage,X-Ca-Supervisor-Token"}
// Body: null

// Response：
// 200
// Date: Sun, 13 Jul 2025 01:39:07 GMT
// Content-Type: application/json; charset=utf-8
// Transfer-Encoding: chunked
// Connection: keep-alive
// Vary: Accept-Encoding
// Access-Control-Allow-Origin: *
// X-Ca-Request-Id: 607E2B56-9DEF-477B-A6BD-6C77353B91EC
// Content-Disposition: attachment; filename=ApiResponseForInnerDomain

// {"data":{"day":{"time":"13日白天","sunUp":"日出
// 05:04","wind":"北风","weather_pic":"d00","temperature":"33","wind_pow":"<3级","weather":"晴"},"night":{"time":"13日夜间","sunDown":"日落
// 19:11","wind":"西北风","weather_pic":"n01","temperature":"27","wind_pow":"<3级","weather":"多云"},"hour3data":["13日11时,d00,晴,32℃,北风,<3级,2","13日14时,d00,晴,32℃,北风,<3级,2","13日17时,d00,晴,33℃,北风,<3级,2","13日20时,n00,晴,30℃,西风,<3级,0","13日23时,n01,多云,28℃,西风,<3级,0","14日02时,n01,多云,28℃,西风,<3级,0","14日05时,n01,多云,27℃,西北风,<3级,0","14日08时,d01,多云,29℃,西北风,<3级,2"],"now":{"WD":"西风","qy":"1003","rain24h":"0","SD":"78%","njd":"8km","rain":"0","wde":"W","sd":"78%","wse":"5km\/h","tempf":"83.3","aqi":"37","date":"07月13日(星期日)","cityname":"京口","aqi_pm25":"37","weathercode":"d18","WS":"2级","temp":"28.5","city":"101190306","weathere":"Foggy","weather":"雾","limitnumber":"","nameen":"jingkou","time":"09:30"},"cityInfo":{"areaCn":"京口","nationCn":"中国","areaId":"101190306","areaCode":"321102","nationEn":"china","cityEn":"zhenjiang","provCn":"江苏","provEn":"jiangsu","areaEn":"jingkou","cityCn":"镇江"},"hour1data":[{"jd":"8","jb":"28","je":"83","jc":"0","jf":"2025071308","ja":"00"},{"jd":"3","jb":"29","je":"79","jc":"0","jf":"2025071309","ja":"00"},{"jd":"5","jb":"30","je":"75","jc":"0","jf":"2025071310","ja":"00"},{"jd":"8","jb":"32","je":"72","jc":"0","jf":"2025071311","ja":"00"},{"jd":"5","jb":"32","je":"70","jc":"0","jf":"2025071312","ja":"00"},{"jd":"3","jb":"32","je":"69","jc":"0","jf":"2025071313","ja":"00"},{"jd":"8","jb":"32","je":"68","jc":"0","jf":"2025071314","ja":"00"},{"jd":"8","jb":"33","je":"67","jc":"0","jf":"2025071315","ja":"00"},{"jd":"8","jb":"33","je":"66","jc":"0","jf":"2025071316","ja":"00"},{"jd":"8","jb":"33","je":"66","jc":"0","jf":"2025071317","ja":"00"},{"jd":"2","jb":"32","je":"73","jc":"0","jf":"2025071318","ja":"00"},{"jd":"4","jb":"31","je":"81","jc":"0","jf":"2025071319","ja":"00"},{"jd":"6","jb":"30","je":"88","jc":"0","jf":"2025071320","ja":"00"},{"jd":"6","jb":"29","je":"90","jc":"0","jf":"2025071321","ja":"00"},{"jd":"6","jb":"29","je":"92","jc":"0","jf":"2025071322","ja":"01"},{"jd":"6","jb":"28","je":"94","jc":"0","jf":"2025071323","ja":"01"},{"jd":"6","jb":"28","je":"93","jc":"0","jf":"2025071400","ja":"01"},{"jd":"6","jb":"28","je":"92","jc":"0","jf":"2025071401","ja":"01"},{"jd":"6","jb":"28","je":"91","jc":"0","jf":"2025071402","ja":"01"},{"jd":"6","jb":"28","je":"90","jc":"0","jf":"2025071403","ja":"01"},{"jd":"7","jb":"27","je":"88","jc":"0","jf":"2025071404","ja":"01"},{"jd":"7","jb":"27","je":"87","jc":"0","jf":"2025071405","ja":"01"},{"jd":"7","jb":"28","je":"86","jc":"0","jf":"2025071406","ja":"01"},{"jd":"7","jb":"28","je":"84","jc":"0","jf":"2025071407","ja":"00"}]},"desc":"成功","code":"0"}